<template>
   <div class="header">
        <div class="flag iconfont icon-fanhui" @click="back"></div>
        <div class="xuanze">
          城市选择
        </div>
        <div class="search">
          <input type="text" v-model="keyword" value="" placeholder="输入城市名或拼音">
        </div>
        <div class="list" ref="wrapper" v-show="keyword"> <!--如果搜索框输入了数据就显示搜索页，否则显示城市页-->
          <ul>
            <li class="border-bottom" v-for="item in serachList" :key="item.id">{{ item.name }}</li>
            <li v-show="hansNoData">没有找到匹配数据</li>  <!--如果输入的城市差找不到，就显示这个 li标签-->
          </ul>
        </div>
   </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'Header',
  data () {
    return {
      keyword: '',
      serachList: [],
      timer: null
    }
  },
  computed: {
    hansNoData () {
      return !this.serachList.length
    }
  },
  methods: {
    // 返回上一页
    back () {
      this.$router.go(-1)
    }
  },
  watch: {
    'keyword': function (newVal) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        if (this.keyword) {
          for (let i in this.cities) {
            this.cities[i].forEach((item) => {
              if ((item.spell.indexOf(this.keyword) > -1) || (item.name.indexOf(this.keyword) > -1)) {
                result.push(item)
              }
            })
          }
        } else {
          this.serachList = []
          return
        }
        this.serachList = result
      }, 100)
    }
  },
  // 接收父组件
  props: ['cities'],
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper)
  }
}
</script>
<style lang="stylus" scoped>
  .flag
    color: #fff
    line-height: 0.86rem
    width: .64rem
    float: left
    text-align center
    font-size 16px
  .xuanze
    text-align center
    line-height:.86rem
    background-color: #00bcd4
    color: #fff
    font-size .32rem
  .search
    background-color: #00bcd4
    text-align center
    padding: 0 .1rem .1rem .1rem
  .search > input
    line-height:.62rem
    width:100%
    border-radius .06rem
    text-align center
  .list
    z-index 1
    overflow: hidden
    position: absolute
    left: 0
    right: 0
    bottom: 0
    top: 1.58rem
    background-color: #eee
    ul > li
      background-color: white
      line-height: .62rem
      padding-left:.2rem
</style>
